package com.issac.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

/**
 * @ClassName JwtUtils
 * @Author zy
 * @Date 2021/10/26 17:53
 * @Description JwtUtils
 * @Version 1.0
 */
public class JwtUtils {
    private static final String secret = "secret";
    private static final long expire = 100000;

    /**
     * @return 生成token
     */
    public static String generateToken(String id) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        // claim:声明
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(id)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret) // 签名算法
                .compact();
        return token;
    }

    /**
     * 解析token获取负载中的声明对象
     */
    public static Claims getClaimByToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }

    // jwt是否过期
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}